const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    act_info: {},
    tuan_id: "",
    is_tuan: false,
    requested: false,

    tuan_name: '',
    tun_card_id: '',
    tuan_phone: '',

    temp_name: '',
    temp_card_id: '',


    agentList: [],
    user_list: [],
    agent_list: [],
    agent: {},
  },

  //下订单
  create_order() {

    let that = this
    let activity_id = this.data.act_info.id
    let tuan_id = this.data.tuan_id
    let age = this.get_age(this.data.tun_card_id)
    let is_tuan = this.data.is_tuan

    // 如果单团---》开团--》提交订单
    if (!is_tuan) {
      // 非团购
      // 开单团
      let singole_tuan = {
        type: 2,
        activity_id,
        name: this.data.tuan_name,
        phone: this.data.tuan_phone,
        idnum: this.data.tun_card_id,
        age,
        tuan_id
      }
      app.request("/user/add_userInfo", {
        method: "post",
        data: singole_tuan
      }).then(res => {
        console.log(res);
        if (res.data.data) {
          if (res.data.msg) {
            wx.showToast({
              title: res.data.msg,
              icon: "none"
            })
          }
          // 开团成功
          this.setData({
            tuan_id: res.data.data
          }, () => {

            // 计算价格
            app.request("/user/qg_calmoney", {
              method: "post",
              data: {
                tuan_id: res.data.data,
                activity_id,
                type: 2
              }
            }).then(res2 => {
              if (res2.data.code == 200) {
                if (res.data.msg) {
                  wx.showToast({
                    title: res.data.msg,
                    icon: "none"
                  })
                }
                let price = res2.data.data
                // 单团下单
                let my_data = {
                  price,
                  activity_id,
                  type: 2,
                  name: this.data.tuan_name,
                  phone: this.data.tuan_phone,
                  distribution_userid: this.data.agent.id,
                  tuan_id
                }
                app.request('/user/add_activity', {
                  method: "post",
                  data: my_data
                }).then(res => {
                  console.log(res, "单团下单");
                  if (res.data.code == 200) {
                    let order_id = res.data.data.order_id
                    that.wxpay(order_id, 2)
                  }
                })
              }
            })
          })
        } else if (res.data.msg) {
          wx.showToast({
            title: res.data.msg,
            icon: "none"
          })
        }

      })


    } else {

      // 团购

      // 计算总价
      app.request("/user/qg_calmoney", {
        method: "post",
        data: {
          tuan_id,
          activity_id,
          type: 4
        }
      }).then(res => {
        // 下单
        if (res.data.code == 200) {
          if (res.data.msg) {
            wx.showToast({
              title: res.data.msg,
              icon: "none"
            })
          }
          let price = res.data.data

          let my_data = {
            type: 4,
            price,
            activity_id,
            name: this.data.tuan_name,
            phone: this.data.tuan_phone,
            distribution_userid: this.data.agent.id,
            tuan_id
          }
          app.request('/user/add_activity', {
            method: "post",
            data: my_data
          }).then(res => {
            console.log(res, "团购下单");
            if (res.data.code == 200) {
              let order_id = res.data.data.order_id
              that.wxpay(order_id, 4)
            }
          })
        }
      })
    }
  },
  get_money() {
    let that = this
    let activity_id = this.data.act_info.id
    let {
      tuan_id
    } = this.data
    app.request("/user/qg_calmoney", {
      method: "post",
      data: {
        tuan_id,
        activity_id,
        type: 4
      }
    }).then(res2 => {
      if (res2.data.code == 200) {
        that.setData({
          'act_info.price': res2.data.data
        })
      }
    })

  },


  // 420325199811076715
  // 17610988835

  agent_change(e) {
    let index = e.detail
    let agent = this.data.agent_list[index]

    this.setData({
      agent
    })
  },


  open_tun(user) {
    let that = this
    app.request("/user/add_userInfo", {
      method: "post",
      data: user
    }).then(res => {
      console.log(res);
      if (res.data.data) {
        if (res.data.msg) {
          wx.showToast({
            title: res.data.msg,
            icon: "none"
          })
        }

        this.setData({
          tuan_id: res.data.data,
          requested: true
        })
        that.get_money()
        console.log(this.data.tuan_id, 'tuanid');
      } else {
        console.log(res);
        this.setData({
          is_tuan: false
        })
        wx.showToast({
          title: res.data.msg,
          icon: "none"
        })
      }
    })
  },


  fetch(id) {
    app.request("/getac_detail", {
      data: {
        id
      }
    }).then(res => {
      console.log(res.data.data[0].distribute_users);
      let agent_list = res.data.data[0].distribute_users
      agent_list = agent_list.map((item, index) => {
        return {
          text: item.username,
          value: index,
          icon: "https://vip.join.ink/" + item.cover,
          id: item.id
        }
      })
      let agent = agent_list[0]

      this.setData({
        act_info: res.data.data[0],
        agent_list,
        agent
      })
    })
  },
  // go_goods_info(e) {
  //   console.log(e);
  //   let id = e.currentTarget.dataset.id
  //   wx.navigateTo({
  //     url: '/pages/goods_info/goods_info?id=' + id,
  //   })
  // }
  //查看经纪人详情信息
  get_agent_detail(e) {
    let id = e.currentTarget.dataset.id
    console.log(e)
    console.log(id)
    app.request("/user/get_leadings_detail", {
      method: "GET",
      data: {
        dis_user_id: id
      }
    }).then(res => {
      if (res.data.code == 200) {
        wx.navigateTo({
          url: '/pages/agent_info/agent_info?id=' + id,
          success: function(res) {
            // 通过eventChannel向被打开页面传送数据
            res.eventChannel.emit('acceptDataFromOpenerPage', { data: id })
          }
        })
      }
    })

  },

  onSwitchChange(e) {
    console.log(e.detail);
    let flg = e.detail
    let {
      tuan_name,
      tun_card_id,
      tuan_phone,
    } = this.data
    let activity_id = this.data.act_info.id
    let age = this.get_age(tun_card_id)

    let user = {
      name: tuan_name,
      idnum: tun_card_id,
      phone: tuan_phone,
      activity_id,
      age,
      type: 4,
    }
    console.log(user);



    if (tuan_name && tun_card_id && tuan_phone) {
      this.setData({
        is_tuan: flg
      })
      if (flg) {
        this.open_tun(user)
      }
    } else {
      wx.showToast({
        title: '请补全团长信息',
        icon: "none"
      })
    }
  },

  order_add() {
    let that = this
    let activity_id = this.data.act_info.id
    let {
      temp_name,
      temp_card_id,
      tuan_id
    } = this.data

    if (!temp_name) {
      wx.showToast({
        title: '姓名不能为空',
      })
    } else if (!temp_card_id) {
      wx.showToast({
        title: '证件号不能为空',
      })
    } else {
      let item = {
        tuan_type: 4,
        tuan_id,
        activity_id,
        name: temp_name,
        idnum: temp_card_id,
        age: that.get_age(temp_card_id)
      }
      console.log(item);
      app.request("/user/add_tuanyuanUser", {
        method: "post",
        data: item
      }).then(res => {
        console.log(res);
        if (res.data.code == 200) {
          let user_list = this.data.user_list
          this.setData({
            user_list: res.data.data
          })


          // 计算金额

          app.request("/user/qg_calmoney", {
            method: "post",
            data: {
              tuan_id,
              activity_id,
              type: 2
            }
          }).then(res2 => {
            if (res2.data.code == 200) {
              that.setData({
                'act_info.price': res2.data.data
              })
            }
          })

          that.get_money()

        } else if (res.data.code == 201) {
          wx.showToast({
            title: '人数已达上限',
            icon: "none"
          })
        } else {
          wx.showToast({
            title: '添加成员失败',
            icon: "none"
          })
        }
      })
    }
  },


  order_reduce(e) {
    let that = this
    console.log(e);
    let i = e.currentTarget.dataset.index
    let arr = this.data.user_list
    let activity_id = this.data.act_info.id
    arr.forEach((item) => {
      if (item.idnum == i) {
        let user = {
          tuan_id: this.data.tuan_id,
          tuan_type: 4,
          activity_id,
          tuan_leader: item.tuan_leader,
          idnum: i
        }
        app.request("/user/del_tuan_activity", {
          method: "post",
          data: user
        }).then(res => {
          console.log(res);
          if (res.data.code == 200) {
            this.setData({
              user_list: res.data.data
            })
            that.get_money()
          } else {
            console.log(res.data.msg);
          }
        })
      }
    })

  },

  get_age(identityCard) {
    var len = (identityCard + "").length
    var strBirthday = ""
    if (len == 18) {
      strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2);
    }
    if (len == 15) {
      var birthdayValue = '';
      birthdayValue = identityCard.charAt(6) + identityCard.charAt(7);
      if (parseInt(birthdayValue) < 10) {
        strBirthday = "20" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
      } else {
        strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
      }
    }
    var birthDate = new Date(strBirthday);
    var nowDateTime = new Date();
    var age = nowDateTime.getFullYear() - birthDate.getFullYear();
    if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
      age--;
    }
    return age;
  },


  // 支付
  wxpay(order_no, type) {
    app.request("/user/activity_pay", {
      method: "POST",
      data: {
        order_no,
        type
      }
    }).then(res => {
      console.log(res, "发起支付");
      let {
        timeStamp,
        nonceStr,
        signType,
        paySign
      } = res.data.data
      let packages = res.data.data.package
      let out_trade_no = res.data.order_id
      wx.requestPayment({
        timeStamp: timeStamp + '',
        nonceStr: nonceStr,
        package: packages,
        signType: signType,
        paySign: paySign,
        fail(err) {
          console.log(err)
          wx.redirectTo({
            url: '/pages/order_list_activity/order_list_activity',
          })
        },
        success(res) {
          console.log(res, "支付成功");
          //查询订单
          app.request("/user/pay/activity_search", {
            method: "POST",
            data: {
              out_trade_no
            }
          }).then(res => {
            console.log(res, "订单查询");
            wx.redirectTo({
              url: '/pages/order_list_activity/order_list_activity',
            })
          })
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.fetch(options.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})